<template>
  <div style="background-color: #f4fafe; min-height: 100vh">
    <div class="header-wrapper">
      <div class="logo-wrapper">
        <!-- <img src="https://s3.kaoshixing.com/static/base/images/ksx-logo-double.svg" /> -->
      </div>
      <div class="exam-name ellipsis">考试示例</div>
      <div class="user ellipsis">
        <i class="icon icon-a_nav_my"></i>
        hh
      </div>
      <a type="button" class="btn btn-default back-icon logout"></a>
    </div>
    <div class="banner-box">
      <div class="title">{{Test.examName}}</div>
     <!-- <div class="info">
        <div class="info-item">总分：{{}}分</div>
        <el-divider direction="vertical"></el-divider>
        <div class="info-item">及格分：60分</div>
        <el-divider direction="vertical"></el-divider>
        <div class="info-item">题数：20道</div>
      </div> -->
      <div class="paizhao">
        <div style="display: flex">
          <div class="videobox">
            <video id="video" class="video" src=""></video>
          </div>
          <div class="preview">
            <canvas id="canvas"></canvas>
          </div>
          <div style="padding: 0 20px">
            <h3>拍照</h3>
            <p style="color: #fff; margin: 15px 0 40px 0">
              * 保证人脸主体清晰，可重复拍照。
            </p>
            <el-button @click="takephoto">点击拍照</el-button>
            <el-button @click="uploadfacephoto">确认并上传</el-button>
          </div>
        </div>
      </div>
      <div class="paizhao">
        <div style="display: flex">
          <div class="idbox">
            <img ref="idcardimg" src="" alt="" style="vertical-align: top" />
            <input ref="idcard" type="file" @change="previewIdCard" />
          </div>
          <div style="padding: 0 20px">
            <h3>上传身份证</h3>
            <p style="color: #fff; margin: 15px 0 40px 0">
              * 点击左边加号选择身份证 <br>
              * 上传身份证带头像的一面 <br>
              * 预览确认清晰后点击确认上传 <br>
            </p>
            <el-button @click="cardUpload">确认上传</el-button>
          </div>
        </div>
      </div>
      <div class="btn-box">
        <div class="button join" @click="goExam">立即考试</div>
      </div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import axios from "axios";
import base64ToBlob from "base64ToBlob";
import { uploadFacePhoto } from "../../request/examapi";
console.log(uploadFacePhoto);
export default {
  name: "Startexam",
  data() {
    return {
      idphoto: false,
      facephoto: false,
      faceFile: "",
      imgurl: "",
      idcard: "",
      isV: false, // 头像和身份证是否验证通过
	  Test:this.$route.params.testid
    };
  },
  mounted() {
    const that = this;
    // var video = this.$refs.video;
    const video = document.getElementById("video");
    //访问摄像头
    if (
      navigator.mediaDevices.getUserMedia ||
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia
    ) {
      //调用用户媒体设备, 访问摄像头
      getUserMedia({ video: { width: 330, height: 212 } }, success, error);
    } else {
      alert("不支持访问摄像头");
    }

    //访问用户媒体设备的兼容方法
    function getUserMedia(constraints, success, error) {
      if (navigator.mediaDevices.getUserMedia) {
        //最新的标准API
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(success)
          .catch(error);
      } else if (navigator.webkitGetUserMedia) {
        //webkit核心浏览器
        navigator.webkitGetUserMedia(constraints, success, error);
      } else if (navigator.mozGetUserMedia) {
        //firfox浏览器
        navigator.mozGetUserMedia(constraints, success, error);
      } else if (navigator.getUserMedia) {
        //旧版API
        navigator.getUserMedia(constraints, success, error);
      }
    }

    //成功回调
    function success(stream) {
      //兼容webkit核心浏览器
      const CompatibleURL = window.URL || window.webkitURL;
      video.srcObject = stream;
      video.play();
      that.video = video; // 保存video
      video.addEventListener("canplay", function () {
        that.videowidth = this.clientWidth;
        that.videoheight = this.clientHeight;
        that.canvas = document.getElementById("canvas");
        that.canvas.setAttribute("width", that.videowidth);
        that.canvas.setAttribute("height", that.videoheight);
        that.context = that.canvas.getContext("2d");
      });
    }

    //失败回调
    function error(error) {
      console.log(error);
      console.log("访问用户媒体设备失败");
    }
    // 强制window 获取焦点
    // window.focus();
    // window.onblur = function(){
    // 	alert('你试图离开当前窗口,系统将自动提交试卷!')
    // }
    // 进入页面后 打开摄像头
  },
  methods: {
    //拍照上传
    uploadfacephoto() {
      const examId = this.Test.id; // 最终通过传参带过来
      const formdata = new FormData();
      // const cutTime = moment().format("YYYY-MM-DD HH:mm:ss");
      // formdata.append("cutTime", cutTime);
      // formdata.append("examId", examId);
      // 将base64 转为 blob
      const faceFile = base64ToBlob(this.faceFile, "image/png");
      formdata.append("faceFile", faceFile);

      const token = window.localStorage.getItem("token");
	  var _that=this;
      axios
        .post("http://101.43.71.61:8080/monitor/registerFace", formdata, {
          Headers: {
            token: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          console.log(res);
          _that.imgurl = res.data.data;

          if (
            typeof res.data === "string" &&
            res.data.indexOf("code=2006") != -1
          ) {
            this.$push({
              name: "Login",
              query: {
                redirect: router.currentRoute.fullPath,
              },
            });
          } else {
            // 进入正常业务逻辑
            this.$message({
              message: res.data.message+' 请验证身份证。',
              type:'success'
            })
          }
        });
    },
    takephoto() {
      this.upload();
    },
    upload() {
      //   const that = this;
      //将视频写入canvas
      this.context.drawImage(
        this.video,
        0,
        0,
        this.videowidth,
        this.videoheight
      );
      //将Canvas的数据转换为base64位编码的PNG图像
      const imageData = this.canvas.toDataURL("image/png");
      //截取22位以后的字符串作为图像数据
      const imgStr = imageData.substr(22);
      this.faceFile = imgStr;
      console.log("截屏数据", imageData);
    },
    cardUpload() {
      // 验证身份证
      const that = this;
      const examId = this.Test.id; // 最终通过传参带过来
      const formdata = new FormData();
      // const cutTime = moment().format("YYYY-MM-DD HH:mm:ss");
      formdata.append("examId", examId);
      formdata.append("faceUrl", this.imgurl);
      formdata.append("cardFile", this.$refs.idcard.files[0]);
      axios
        .post(
          "http://101.43.71.61:8080/monitor/uploadCardAndCompare",
          formdata,
          {
            Headers: {
              token: localStorage.getItem("token"),
            },
          }
        )
        .then((res) => {
          console.log(res);
          this.imgurl = res.data.data;

          if (
            typeof res.data === "string" &&
            res.data.indexOf("code=2006") != -1
          ) {
            this.$push({
              name: "Login",
              query: {
                redirect: router.currentRoute.fullPath,
              },
            });
          } else {
            // 身份证验证通过
            that.isV = true;
          }
        });
    },
    previewIdCard() {
      // 预览
      const idcard = this.$refs.idcard.files[0];
      const fd = new FileReader();
      fd.readAsDataURL(idcard);
      const that = this;
      fd.onload = function () {
        that.$refs.idcardimg.src = fd.result;
      };
    },
    goExam() {
      if (this.isV) {
        this.$router.push({
          name: "examination",
        });
      }else{
        this.$message({
          message:'请拍照并验证身份证',
          type:'warning'
        })
      }
    },
  },
  created()
  {
	  // console.log(this.Test,"云儿");
	  localStorage.setItem("Test",JSON.stringify(this.Test));
  }
};
</script>

<style scoped="scoped">
.header-wrapper {
  box-sizing: border-box;
  height: 70px;
  width: 100%;
  line-height: 70px;
  padding-left: 220px;
  padding-right: 400px;
  background: #ffffff;
  box-shadow: 0 2px 4px 0 rgb(153 153 153 / 10%);
  /* position: fixed; */
  top: 0;
  left: 0;
  z-index: 1040;
}

.banner-box {
  width: 1200px;
  margin: 40px auto;
  min-height: 262px;
  background: -webkit-linear-gradient(left, #03d3bd, #00dbcf);
  box-shadow: 0 4px 8px 0 hsl(0deg 0% 40% / 10%);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}

.title {
  width: 100%;
  text-align: center;
  height: 28px;
  font-size: 20px;
  font-weight: 600;
  color: #fff;
  line-height: 28px;
  margin-top: 50px;
  margin-bottom: 30px;
}

.info {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  margin-bottom: 50px;
}

.info-item {
  height: 14px;
  font-size: 14px;
  font-weight: 400;
  color: #fff;
  line-height: 14px;
}

.btn-box {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.button.join {
  width: 104px;
  height: 40px;
  margin-top: 1.25rem;
  margin-bottom: 1.25rem;
  line-height: 2.5rem;
  background: #fff;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 400;
  text-align: center;
  color: #03d3bd;
  cursor: pointer;
}

.header-wrapper .logo-wrapper {
  height: 100%;
  width: 211px;
  position: absolute;
  left: 0;
  top: 0;
  text-align: right;
}

img,
audio,
video,
iframe {
  max-width: 100%;
}

img {
  vertical-align: middle;
}

.header-wrapper .exam-name {
  font-size: 18px;
  color: #27274a;
  padding-left: 20px;
}

.ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.header-wrapper .user {
  position: absolute;
  right: 210px;
  top: 0;
  max-width: 160px;
}

.header-wrapper .user .icon {
  color: #1a8cfe;
  font-size: 16px;
  margin-right: 7px;
  line-height: 70px;
}

.icon[class*="icon-a_"],
.icon[class*="icon-p_"],
.icon[class*="icon-m_"] {
  position: relative;
  top: 1px;
}

.btn {
  display: inline-block;
  margin-bottom: 0;
  font-weight: normal;
  text-align: center;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  background-image: none;
  border: 1px solid transparent;
  white-space: nowrap;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.42857143;
  border-radius: 4px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
.paizhao {
  border: 1px solid #aaa;
  margin-top: 0.625rem;
  width: 80%;
  margin: 0 auto;
}
.idbox {
  width: 400px;
  height: 250px;
  position: relative;
  border: 2px dashed #fff;
  border-radius: 5px;
}
.idbox::before {
  content: "+";
  position: absolute;
  width: 100%;
  height: 100%;
  color: #fff;
  font-size: 100px;
  text-align: center;
  line-height: 250px;
}
.idbox input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid #000;
  opacity: 0;
}
.idbox img {
  position: relative;
  widows: 100%;
  height: 100%;
}
h3 {
  color: #fff;
}
</style>
